<template>
  <div>
    <el-upload
      :action="uploadURL"
      list-type="picture-card"
      :limit="limit"
      :on-exceed="handleimgsExceed"
      :file-list="imagesfilelist"
      :on-success="handleImgsSuccess"
      :on-remove="handleImgsRemove"
    >
      <i slot="default" class="el-icon-plus" />
    </el-upload>
  </div>
</template>

<script>
export default {
  name: 'ImgUpload',
  props: {
    images: {
      type: Array,
      default: null
    },
    limit: {
      type: Number,
      default: 10
    }
  },
  data() {
    return {
      uploadURL: process.env.VUE_APP_BASE_API + '/common/upload',
      imagesData: [],
      imagesfilelist: [],
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  created() {
    this.imagesData = this.images
    for (let i = 0; i < this.imagesData.length; i++) {
      var j = {}
      j.url = this.imagesData[i]
      this.imagesfilelist.push(j)
    }
  },
  methods: {
    handleImgsSuccess(res) {
      this.imagesData.push(res.data.fullurl)
      console.log(res)
      this.$emit('handleImgs', this.imagesData)
    },
    handleImgsRemove(file) {
      if (file.name) {
        delimg = file.response.data.url
        for (let i = 0; i < this.imagesData.length; i++) {
          if (delimg === this.imagesData[i]) {
            this.imagesData.splice(i, 1)
          }
        }
      } else {
        var delimg = file.url
        for (let i = 0; i < this.imagesData.length; i++) {
          if (delimg === this.imagesData[i]) {
            this.imagesData.splice(i, 1)
          }
        }
      }
      this.$emit('handleImgs', this.imagesData)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleimgsExceed() {
      this.$message({
        message: `最多上传${this.limit}张`,
        type: 'warning'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.el-upload--picture-card,
.el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 104px;
}
.el-upload-list__item {
  .el-icon-check {
    position: absolute;
    top: 0px;
    right: 13px;
  }
}
</style>
